<?php 

require_once  __DIR__ . '/includes/authenticate.php';

?>

<div class="row">
<div class="col-md-1"></div>
<div class="col-md-9">
<h2>Results</h2>
<table class="table table-hover table-striped">
    <thead>
      <tr>
        <th>Date</th>
        <th colspan="2">Game</th>
        <th>Result</th>
        </tr>
    </thead>
    <tbody>
     
<?php

include_once './db_bb_connect.php';

if(isset($_POST['location']) OR isset($_POST['opponent']) OR isset($_POST['datemin']) OR isset($_POST['datemax']) OR isset($_POST['result'])) {

$sql = "SELECT * FROM games WHERE ";

$post = array();

foreach($_POST as $key=>$value)
{
  //echo "$key= " . print_r($value);
  $post["$key"] = $value;
}

//print_r($post);

$addsql = "";

foreach($post as $key=>$value)
{     
	for ($x = 0; $x < count($post["$key"]); $x++){

		if ($key === "opponent"){
			
			if (count($post["opponent"]) === 1) {
				
				$addsql .= "AND ( $key = '" . $post["$key"][$x] . "' ";

			} else {
				if ($x == 0) {
					$addsql .= "AND ( $key = '" . $post["$key"][$x] . "' ";
				} else {
					$addsql .= "OR $key = '" . $post["$key"][$x] . "' ";
					}
				}
			if ($x === (count($post["opponent"])-1)){
					$addsql .= ") ";	
			}
		} else if ($key === "location") {
			
			if (count($post["location"]) === 1) {
				
				$addsql .= "AND ( $key = '" . $post["$key"][$x] . "' ";

			} else {
				if ($x == 0) {
					$addsql .= "AND ( $key = '" . $post["$key"][$x] . "' ";
				} else {
					$addsql .= "OR $key = '" . $post["$key"][$x] . "' ";
					}
				}
			if ($x === (count($post["location"])-1)){
					$addsql .= ") ";	
			} 
		} else if ($key === "result") {
				if ($post["result"][$x] === 'wins') {
					$addsql .= " AND score_exc_tot > score_opp_tot ";
				} elseif ($post["result"][$x]  === 'losses') {
					$addsql .= " AND score_exc_tot < score_opp_tot ";
				} 
		} else if ($key === "datemin" OR $key === "datemax" ) {

		} else {
			if ($x == 0) {
			$addsql .= "AND $key = '" . $post["$key"][$x] . "' ";
		} else {
			$addsql .= "OR $key = '" . $post["$key"][$x] . "' ";
			}
		}
	}
}


$sql .= ltrim($addsql,"AND ");

}

else {
	$sql = "SELECT * FROM games";
}


$sql .= " ORDER BY date";
$result=$db->query($sql);


while($row=$result->fetch_assoc()){	
	$date = $row['date']; 
	$opponent = $row['opponent']; 
	$location = $row['location']; 
	$score_exc = $row['score_exc_tot']; 
	$score_opp = $row['score_opp_tot'];
	//$statsav = $row['statsavailable'];

	echo "<tr>";
    echo "<td>$date</td>";
          
	if ( $location == 'home' ) {

		echo "<td> Exercitia U20 </td>";
		echo "<td> $opponent </td>";
		echo "<td>$score_exc - $score_opp</td>";

	}
	else { 
		echo "<td> $opponent </td>";
		echo "<td> Exercitia U20 </td>"	;	
		echo "<td>$score_opp - $score_exc</td>";
	}

	//echo "<td>$statsav</td>";
	echo "</tr>";

}

?>

    </tbody>
  </table>



  </div>
<div class="col-md-1"></div>
</div>

